package com.ustadzmenjawab.server;

import java.io.IOException;
import net.sf.classifier4J.summariser.SimpleSummariser;
import org.apache.lucene.analysis.Analyzer;
//import org.apache.lucene.analysis.id.IndonesianAnalyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.util.Version;

import com.ustadzmenjawab.indexing.UstadzMenjawabSynAnalyzer;
import com.ustadzmenjawab.shared.Constant;

public class FragmentUtil {
	public static final int FRAGMENT_NUM = 2;
	public static final int MAX_FRAGMENT_SIZE = 100;
	public static String[] getFragmentsWithHighlightedTerms(Analyzer analyzer, Query query, String fieldName, String fieldContents, int fragmentNumber, int fragmentSize) throws IOException {
		//TokenStream stream = TokenSources.getTokenStream(fieldName, fieldContents, analyzer);
		//SpanScorer scorer = new SpanScorer(query, fieldName,new CachingTokenFilter(stream));
		QueryScorer scorer = new QueryScorer(query,fieldName);
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer, fragmentSize);
		
		Highlighter highlighter = new Highlighter(scorer);
		highlighter.setTextFragmenter(fragmenter);
		highlighter.setMaxDocCharsToAnalyze(Integer.MAX_VALUE);

		//String[] fragments = highlighter.getBestFragments(stream, fieldContents, fragmentNumber);
		String[] fragments = null;
		try {
			fragments = highlighter.getBestFragments(new UstadzMenjawabSynAnalyzer(Version.LUCENE_35),fieldName,fieldContents,fragmentNumber);
			return fragments;
		} catch (InvalidTokenOffsetsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return fragments;
	}
	public static String getBestFragments (String keyword, String text){
		String querystr = keyword;
		QueryParser parser = new QueryParser(Version.LUCENE_35,"artikel",new UstadzMenjawabSynAnalyzer(Version.LUCENE_35));
		parser.setFuzzyMinSim(Constant.FUZZY_MIN_SIM);
		parser.setFuzzyPrefixLength(Constant.FUZZY_PREFIX_MAX);
		
		try {
				Query q = parser.parse(querystr);
				String[] fragment =  getFragmentsWithHighlightedTerms(new UstadzMenjawabSynAnalyzer(Version.LUCENE_35),q, "artikel", text, FRAGMENT_NUM, MAX_FRAGMENT_SIZE);
				if(fragment == null || fragment.length == 0){
					SimpleSummariser summariser = new SimpleSummariser();
					String result= summariser.summarise(text, 1);
					if(result.length() > FRAGMENT_NUM * MAX_FRAGMENT_SIZE){
						result = result.substring(0, FRAGMENT_NUM * MAX_FRAGMENT_SIZE);
					}
					return result;
				}
				String ret = "";
				if(fragment != null)
				for(String f : fragment){
					ret += f.replace("\n", " ") +"...";
				}
				if(ret.length() > 0)
					return ret.toLowerCase();
			} catch (IOException e) {
				
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		return "...";
	}
	
	/*
	public static String getBestFragments (String keyword, String text){
		String[] terms = keyword.split(" ");
		String snippet ="";
		int scope = 10;
		int iterate = 1;
		int startIterate = 0;
		text = text.toLowerCase();
		for(int it = 0 ; it < iterate;it++){
			int indpos = -1;
			if(it > 0)
				snippet += "...";
			for(String term : terms){
				term = term.replace("\"", "").toLowerCase();
				if(term.length() > 3){
					if(!snippet.contains(term)){
						indpos = text.indexOf(term);
						if(indpos == -1)
							continue;

						int endpos = indpos;
						int startpos = find2WordBefore(text, indpos,scope);
						if(startpos == -1)
							startpos = indpos;
						for(int i = 0 ; i <= scope;i++){
							endpos = text.indexOf(" ", endpos+1);
						}
						if(startpos <  endpos ){

							snippet += text.substring(startpos, endpos).replace(term, "<b>"+term+"</b>")+"...";
							startIterate = endpos+1;
						}
					}else{
						snippet = snippet.replace(term, "<b>"+term+"</b>");
					}
				}
			}
		}
		if(snippet.length() > 0)
			return snippet;
		return snippet+" ...";
	}
	*/
	/*
	private static int find2WordBefore(String text , int ind, int scope){
		int count = 0;
		int i = ind - 1;
		for(i = ind-1 ; i > 0 ; i--){
			if(text.charAt(i) == ' '){
				count++;
				if(count == scope+1){
					return i;
				}
			}
		}
		return -1;
	}
	*/
}
